﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SmartUwriteDowloadApp
{
    public partial class MainForm : Form
    {
        //http://download.bimt.com/SmartUwrite_for_x64_office.exe

        string url = @"http://download.bimt.com/SmartUwrite_for_x86_office.exe";
        string fileName = "SmartUwrite_for_x86_office.exe";
        string size = "size";
        string dir = string.Empty;
        bool downloadComplete = false;
        List<Image> listImage = new List<Image>();
        public MainForm()
        {
            InitializeComponent();
        }

        public delegate void InitItemInvoke(string str);
        public delegate void InstallApp(string str);
        int times = 0;
        public void DoWord()
        {
            try
            {
                if (File.Exists(dir + "\\" + fileName))
                {
                    File.Delete(dir + "\\" + fileName);
                }
                InitItemInvoke mi = new InitItemInvoke(SetProcessValue);
                InstallApp install = new InstallApp(Downloadcomplete);
                while (true)
                {
                    Thread.Sleep(1000);
                    if (File.Exists(dir + "\\" + fileName))
                    {
                        FileInfo fi = new FileInfo(dir + "\\" + fileName);
                        string result = fi.Length.ToString();// 
                        if (downloadComplete)
                        {
                            times++;
                            if (times==3)
                            {//3秒文件大小不变中断循环
                                BeginInvoke(install, new object[] { result });
                                break;
                            }
                           
                           
                        }
                        else
                        {
                            BeginInvoke(mi, new object[] { result });
                        }
                        size = result;
                    }
                }


            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void Downloadcomplete(string str)
        {
            try
            {
                //lab_size.Text = "OK";
                this.Text = "SmartUwrite DownloadComplete";
                pb_prograss.Value = pb_prograss.Maximum;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

        }

        private void SetProcessValue(string str)
        {
            try
            {
                float ff = float.Parse(str);
                //lab_size.Text = Math.Round((ff / 1024.0 / 1024.0), 2).ToString() + " MB"; ;
                this.Text = "SmartUwrite " + Math.Round((ff / 1024.0 / 1024.0), 2).ToString() + " MB";
                if ((int)(ff / 1024 / 1024) > pb_prograss.Maximum)
                {
                    pb_prograss.Value = pb_prograss.Maximum;
                }
                else
                {
                    pb_prograss.Value = (int)(ff / 1024 / 1024);
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        public void DoProecess()
        {
            try
            {

                Thread threadDownLoad = new Thread(new ThreadStart(DownLoad));
                threadDownLoad.Start();

                Thread thread = new Thread(new ThreadStart(DoWord));
                thread.Start();

                //byte[] array = wc.DownloadData(url);
                //File.WriteAllBytes(fileName, array);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public Process GetWordProcess()
        {
            try
            {
                Process[] arrayP = Process.GetProcesses();//.GetProcessesByName("WINWORD.EXE*32");
                foreach (Process item in arrayP)
                {
                    if (item.ProcessName.ToUpper().Contains("WINWORD"))
                    {
                        return item;
                    }
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    Process p = GetWordProcess();
                    if (p != null)
                    {
                        if (MessageBox.Show("请关闭WORD后运行下载软件！是否关闭WORD?", "软件下载", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (p!=null)
                            {
                                p.Kill();
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                catch (Exception)
                {
                    
                }
               
                if (pb_prograss.Value!=0&&pb_prograss.Value!=pb_prograss.Maximum)
                {
                    MessageBox.Show("正在下载中...");
                    return;
                }
                btn_download.Enabled = false;
                DoProecess();
                //if (fbd_downpath.ShowDialog() == DialogResult.OK)
                //{
                //    dir = fbd_downpath.SelectedPath;
                //    DoProecess();
                //}
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 判断系统位数 假如为64位返回true
        /// </summary>
        /// <returns></returns>
        //public bool Is64Windows() {
        //    try
        //    {
        //        bool type;
        //        type = Environment.Is64BitOperatingSystem;
        //        return type;
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}

        public bool CheckXP() {
            try
            {
                System.OperatingSystem osInfo = System.Environment.OSVersion;

                //获取操作系统ID
                System.PlatformID platformID = osInfo.Platform;

                //获取主版本号
                int versionMajor = osInfo.Version.Major;
                if (versionMajor==5)
                {
                    return true;

                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void DownLoad()
        {
            try
            {
                bool x64office = false;
                WebClient wc = new WebClient();
                //bool x64win = Is64Windows();
                int value = -1;// CheckNonWoW64();
                if (value == 0)
                {
                    value = CheckWoW64();
                }

                if (value > 0)
                {
                    x64office = true;

                }
                else if (value < 0)
                {
                    x64office = false;
                }
                else
                {
                    System.Diagnostics.Process.Start("http://smartuwrite.bimt.com/details.html");
                    throw new Exception("无法判断office位数，请按照说明选择安装程序。");
                }

                //MessageBox.Show("x64office:"+x64office);
                if (x64office)
                {
                    url = @"http://download.bimt.com/SmartUwrite_for_x64_office.exe";
                    fileName = @"SmartUwrite_for_x64_office.exe";
                }
                Uri uri = new Uri(url);
                wc.DownloadFileAsync(uri, dir + "\\" + fileName);//.DownloadFile
                wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
                //btn_download.Enabled = true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
           
        }

        private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {//下载完成安装文件
            try
            {
                downloadComplete = true;
                System.Diagnostics.Process.Start(dir + "\\" + fileName);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 校验guid是否为x64的code
        /// 假如为x64返回true
        /// {BRMMmmmm-PPPP-LLLL-p000-} D000000FF1CE
        /// p	0 为 x86、 x64 的 1	0-1
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool Isx64Code(string code)
        {
            try
            {

                //MessageBox.Show("code" + code);
                string[] array = code.Split('-');
                if (array[3].Contains("1"))
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }


        public int CheckWoW64()
        {

            try
            {
                int x64 = 0;
                string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
                string[] subkeyNames;
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey software = hkml.OpenSubKey(subKey);
                subkeyNames = software.GetSubKeyNames();
                //MessageBox.Show(subKey.ToString());

                //取得该项下所有子项的名称的序列，并传递给预定的数组中  
                foreach (string keyName in subkeyNames)
                //遍历整个数组  
                {
                    //0000000FF1CE
                    //0000000FF1CE
                    
                    if (keyName.ToUpper().Contains("0000000FF1CE"))
                    //判断子项的名称  
                    {
                        string word = hkml.OpenSubKey(subKey + "\\" + keyName).GetValue("DisplayName").ToString();
                        if (word.ToUpper().Contains("WORD"))
                        {
                            //MessageBox.Show(word);
                            bool ok = Isx64Code(keyName);
                            if (ok)
                            {
                                x64 = 1;
                            }
                            else
                            {
                                x64 = -1;
                            }
                            hkml.Close();
                            break;
                        }
                    }
                }
                hkml.Close();
                return x64;
            }
            catch (Exception)
            {

                throw;
            }
        }

        //public int CheckNonWoW64()
        //{

        //    try
        //    {
        //        int x64 = 0;
        //        string subKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
        //        string[] subkeyNames;
        //        RegistryKey hkml = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        //        RegistryKey software = hkml.OpenSubKey(subKey);
        //        subkeyNames = software.GetSubKeyNames();

        //        //取得该项下所有子项的名称的序列，并传递给预定的数组中  
        //        foreach (string keyName in subkeyNames)
        //        //遍历整个数组  
        //        {
        //            if (keyName.ToUpper().Contains("0000000FF1CE"))
        //            //判断子项的名称  
        //            {
        //                RegistryKey local = hkml.OpenSubKey(subKey + "\\" + keyName);
        //                string word = local.GetValue("DisplayName").ToString();
        //                if (word.ToUpper().Contains("WORD"))
        //                {
        //                    //MessageBox.Show(word);
        //                    bool ok = Isx64Code(keyName);
        //                    if (ok)
        //                    {
        //                        x64 = 1;
        //                    }
        //                    else
        //                    {
        //                        x64 = -1;
        //                    }
        //                    software.Close();
        //                    break;
        //                }
        //            }
        //        }
        //        //MessageBox.Show(x64.ToString());
        //        return x64;
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}


        int index = 0;
        int count = 0;
        /// <summary>
        /// 获取下一个image
        /// wuhailong
        /// 2016-08-17
        /// </summary>
        /// <returns></returns>
        public Image GetNextImage()
        {
            try
            {
                Image image = null;
                index = count% listImage.Count ;
                image = listImage[index];
                count++;
                if (count > listImage.Count)
                {
                    count = 1;
                }
                return image;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public void InitData() {
            try
            {
                listImage.Add(Properties.Resources.ad1_1);
                listImage.Add(Properties.Resources.ad2);
                listImage.Add(Properties.Resources.snsx);
                listImage.Add(Properties.Resources.ad4);
                listImage.Add(Properties.Resources.thps);
                //listImage.Add(Properties.Resources._6);
                ////listImage.Add(Properties.Resources._7);
                //listImage.Add(Properties.Resources._8);
                //listImage.Add(Properties.Resources._9);
                //listImage.Add(Properties.Resources._10);
                //listImage.Add(Properties.Resources._11);
                //listImage.Add(Properties.Resources._12);
                count = listImage.Count;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
               //MessageBox.Show("无法判断office位数，请按照说明选择安装程序。");
                InitData();
                dir = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\";
               
            }
            catch (Exception)
            {
                //MessageB
            }
          
            //foreach (Image item in il_info.Images)
            //{
            //    Thread.Sleep(2000);
            //    pic_info.Image = item;
            //}
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            pic_info.Image = GetNextImage();
        }

        private void btn_open_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Explorer.exe", dir);
        }

        private void pic_info_MouseHover(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void pic_info_MouseLeave(object sender, EventArgs e)
        {
            Thread.Sleep(1000);
            pic_info.Image = GetNextImage();
            timer1.Enabled = true;
        }

        private void pic_info_Click(object sender, EventArgs e)
        {
            try
            {
                string adurl = string.Empty;
                //string switch_on = pic_info.Image.
                switch (index)
                {
                    case 0:
                        adurl = "www.bimt.com";
                        break;
                    case 1:
                        adurl = "j.bimt.com";
                        break;
                    case 2:
                        adurl = "paper.bimt.com";
                        break;
                    case 3:
                        adurl = "smartuwrite.bimt.com";
                        break;
                    case 4:
                        adurl = "peer.bimt.com";
                        break;
                    default:
                        adurl = "www.bimt.com";
                        break;
                }
                System.Diagnostics.Process.Start("iexplore", adurl);
            }
            catch (Exception ex)
            {

            }
           
        }

        private void MainForm_Click(object sender, EventArgs e)
        {
            
        }

        private void pb_prograss_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("无法判断office位数，请按照说明选择安装程序。");
        }
    }
}
